﻿using AutoMapper;
using Face8280WebSocketServer.DB.Device;
using Face8280WebSocketServer.DB.NewModel.Device;
using Face8280WebSocketServer.DTO;
using Face8280WebSocketServer.DTO.FaceDevice;
using Face8280WebSocketServer.Interface;
using Face8280WebSocketServer.Utility.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Face8280WebSocketServer.Service
{
    public class FaceDriveServiceNew : BaseService, IFaceDriveServiceNew
    {
        IMapper _Mapper;
        private ICacheService _Cache;
        public FaceDriveServiceNew(DbContext context, IMapper mapper, ICacheService cache) : base(context)
        {
            _Mapper = mapper;
            _Cache = cache;
        }
        /// <summary>
        /// 分页查询设备信息
        /// </summary>
        /// <returns></returns>
        public PageResult<DB.Device.FaceDeviceDetail_PageModel> GetDevicePage(List<Expression<Func<FaceDeviceInfo, bool>>> oWheres, BasePageParameter page)
        {
            var devices = QueryPage(
            x => new DB.Device.FaceDeviceDetail_PageModel()
            {
                ID = x.Id,
                DeviceID = x.DeviceSn,
                DeviceName = x.DeviceName,
                DeviceIP = x.DeviceIP,
                DevicePort = x.DevicePort,
                ConnectType = x.ConnectType,
                ParameterAccessType = x.Door,
                ParameterKeepOpenDoor = x.ReleaseTime,
                ParameterLaissezSwitch = x.Free,
                ParameterProductionDate = DateTime.Now.ToDateTimeStr(),
                ParameterFirmwareMsg = "v15.0"
            },
            oWheres, page.pageSize, page.pageIndex,
            x => x.DeviceSn,
            page.isAsc);
            if (devices.DataList.Count > 0)
                _Cache.GetDeviceOnlineStatus(devices.DataList);
            return devices;
        }

        public List<FaceDeviceStatus> GetDeviceOnlineStatus(List<string> SNList)
        {
            //  List<DB.Device.FaceDeviceDetail_PageModel> oModel = SNList.Select(x => new DB.Device.FaceDeviceDetail_PageModel() { DeviceID = x }).ToList();

            //  return _Cache.GetDeviceOnlineStatus(oModel);

            return _Cache.GetDevices();
        }

        public List<FaceDeviceInfo> GetFaceDevicesByConnectTyep(int type)
        {
            return Set<FaceDeviceInfo>().Where(a => a.ConnectType == type).ToList();
        }
        //public void AddDevice(FaceDeviceDetailNew device)
        //{
        //    var entity = Set<FaceDeviceDetailNew>();
        //    var dbDevice = entity.FirstOrDefault(a => a.DeviceId == device.DeviceId);
        //    if (dbDevice == null)
        //    {
        //        Insert(device);
        //    }
        //    else
        //    {
        //        _Mapper.Map(dbDevice, device);
        //        Commit();
        //    }
        //}
        public JsonResultModel AddDevice(FaceDeviceInfo info)
        {
            if (info == null)
            {
                return new JsonResultModel(101, "设备信息不能为空");
            }
            var dbSet = Set<FaceDeviceInfo>();
            var deviceInfo = dbSet.FirstOrDefault(a => a.Id.Equals(info.Id));
            if (deviceInfo == null)
            {
                Insert(info);
            }
            else
            {
                _Mapper.Map(info, deviceInfo);
                Commit();
            }
            return new JsonResultModel();

        }

        public List<FaceDeviceInfo> GetAllList()
        {
            return Set<FaceDeviceInfo>().ToList();
        }
        public void AddDeviceNetWorker(FaceDeviceNetWork netWork)
        {
            if (netWork == null) return;
            var entity = Set<FaceDeviceNetWork>();
            var dbNetWork = entity.FirstOrDefault(a => a.DeviceId == netWork.DeviceId);
            if (dbNetWork == null)
            {
                Insert(netWork);
            }
            else
            {
                _Mapper.Map(netWork, dbNetWork);
                Commit();
            }
        }

        public void DeleteDevice(int id)
        {
            var entity = Set<FaceDeviceInfo>().FirstOrDefault(a => a.Id == id);
            if (entity != null)
                Delete(entity);
        }
        public void DeleteDeviceRange(int[] id)
        {
            //var idSplit = id.TrimEnd(',').Split(',');
            //var idArray = Array.ConvertAll(idSplit, a => int.Parse(id));
            var entityList = Set<FaceDeviceInfo>().Where(a => id.Contains(a.Id)).ToList();
            foreach (var entity in entityList)
            {
                Delete(entity);
            }

        }

        public void DeleteDevice(string id)
        {
            var entity = Set<FaceDeviceDetailNew>().FirstOrDefault(a => a.DeviceId == id);
            if (entity != null)
                Delete(entity);
        }


        public void DeleteDeviceNetWorker(int DeviceId)
        {
            var entity = Set<FaceDeviceNetWork>().FirstOrDefault(a => a.DeviceId == DeviceId);
            if (entity != null)
                Delete(entity);
        }

        public UpdateDeviceDetailParameter GetFaceDeviceById(string id)
        {
            var info = Set<FaceDeviceInfo>().AsNoTracking().FirstOrDefault(a => a.DeviceSn.Equals(id));
            if (info != null)
            {
                var result = _Mapper.Map<UpdateDeviceDetailParameter>(info);
                result.OldDeviceSn = info.DeviceSn;
                result.Id = info.Id;
                return result;
            }
            return null;
        }

        public FaceDeviceInfo GetFaceDeviceById(int id)
        {
            return Set<FaceDeviceInfo>().FirstOrDefault(a => a.Id == id);
        }

        public string GetDefaultSn()
        {
            int id = 0;
            var tb = Set<FaceDeviceInfo>();
            while (true)
            {
                id++;
                var sn = "FC-8280T" + id.ToString().PadLeft(8, '0');
                if (!tb.Any(a => a.DeviceSn.Equals(sn)))
                {
                    return sn;
                }
            }
        }

        public void UpdateNetWork(WriteNetWorkParameter parameter)
        {
            var device = Find<FaceDeviceInfo>(parameter.DeviceId);
            if (device == null)
            {
                return;
            }
            device.IIp = parameter.IIp;
            device.IMac = parameter.IMac;
            device.IGateway = parameter.IGateway;
            device.IDhcp = parameter.IDhcp;
            device.IMask = parameter.IMask;
            device.IDns = parameter.IDns;
            device.IUdp = parameter.IUdp;
            device.ITcp = parameter.ITcp;
            device.IWebsocket = parameter.IWebsocket;
            device.IKeepalive = parameter.IKeepalive;
            device.ISsl = parameter.ISsl;

            //device.WSServer=parameter.WSServer;
            //device.WSPort=parameter.WSPort;
            //device.WSToken=parameter.WSToken;
            //device.WSServerSSLCert=parameter.WSServerSSLCert;
            //device.WSStatus=parameter.WSStatus;
            //device.WSKeepalive=parameter.WSKeepalive;
            //device.WSKeeptime=parameter.WSKeeptime;
            //device.WSReconnectTime=parameter.WSReconnectTime;

            device.WiFiUse = parameter.WiFiUse;
            device.WiFiName = parameter.WiFiName;
            device.WiFiPassword = parameter.WiFiPassword;
            device.WiFiIp = parameter.WiFiIp;
            device.WiFiMask = parameter.WiFiMask;
            device.WiFiGateway = parameter.WiFiGateway;
            Commit();
        }
    }
}
